home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / lang / c++-part1 / 1334 < prev    next >
Encoding:
Text File  |  1996-08-06  |  1.5 KB  |  90 lines

  1. Path: ecmwf.int!munin!mab
  2. From: mab@ecmwf.co.uk (Baudouin Raoult)
  3. Newsgroups: comp.lang.c++
  4. Subject: locking
  5. Date: 10 Jan 1996 14:41:31 GMT
  6. Organization: European Centre for Medium Range Weather Forecasts
  7. Message-ID: <4d0j6r$1ri@daphne.ecmwf.int>
  8. NNTP-Posting-Host: munin.ecmwf.int
  9. X-Newsreader: TIN [version 1.2 PL2]
  10.  
  11. Hello,
  12.  
  13. I have an interesting problem. I would like to create an object
  14. in shared memory, and lock/unlock it when accessing it:
  15.  
  16. class foo {
  17. public:
  18.     void bar();
  19. };
  20.  
  21. void main()
  22. {
  23.     SharedObject<foo> fooH;
  24.  
  25.     fooH->bar();
  26. }
  27.  
  28. When calling foo::bar, a lock must be set and reset. Using the
  29. operator-> does not help, because I cannot write
  30.  
  31. SharedObject::operator->()
  32. {
  33.     lock();
  34.     return object;
  35.     unlock();
  36. }
  37.  
  38. because the unlock is never executed. I solved my problem by adding
  39. a temporary object:
  40.  
  41. SharedObject::operator->()
  42. {
  43.     return LockObject(object);
  44. }
  45.  
  46. with
  47.  
  48. LockObject::LockObject(o) : object(o)
  49. {
  50.     lock();
  51. }
  52.  
  53. LockObject::~LockObject()
  54. {
  55.     unlock();
  56. }
  57.  
  58. LockObject::operator->()
  59. {
  60.     return object;
  61. }
  62.  
  63. This seems to work, but the LockObject is only destroyed at the
  64. end of the block, locking my object for too long.
  65.  
  66. main()
  67. {
  68.  
  69.     SharedObject<foo> fooH("lock");
  70.     
  71.     ... the lock is not set
  72.     
  73.     fooH->bar();
  74.  
  75.     .. the lock is set until the end.
  76. }
  77.  
  78. Anyone got an idea ?
  79.  
  80. Thanks,
  81. Baudouin
  82.  
  83. --
  84.  
  85. ---------------------------------------------------
  86. Baudouin Raoult. 
  87. European Center for Medium Range Weather Forecast
  88. Reading, UK
  89. ---------------------------------------------------
  90.